package com.sxj.base.util.tree;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;


/**
 * @author Sun Xiaojie
 */
public class TreeUtil<E> {

	/**
	 *
	 * @param list
	 * @param className
	 * @return
	 */
	public List<E> createTree(List<E> list, String className) {
		List<E> tree = new ArrayList<>();
		tree = findRoots(list, className);
		return tree;
	}

	/**
	 * 获取list中的第一级数据
	 * @param list
	 * @return
	 */
	private List<E> findRoots(List<E> list, String className) {
		List<E> roots = new ArrayList<>();
		//list.removeAll(roots);
		for (E e : list) {

			Object ot = null;
			try {
				ot = Class.forName(className).newInstance();
			} catch (InstantiationException e3) {
				// TODO Auto-generated catch block
				e3.printStackTrace();
			} catch (IllegalAccessException e3) {
				// TODO Auto-generated catch block
				e3.printStackTrace();
			} catch (ClassNotFoundException e3) {
				// TODO Auto-generated catch block
				e3.printStackTrace();
			}
	        Class c = ot.getClass();
	        Field[] fields = c.getDeclaredFields();
			Boolean isRoot = true;
			for (Field field : fields) {

				field.setAccessible(true);
				//获取父级属性的值
				//field.get
				boolean hasFatherAnnot = field.isAnnotationPresent(father.class);
				if (!hasFatherAnnot) {
					continue;
				}
				Object fatherValue = null;
				try {
					fatherValue = field.get(e);
				} catch (IllegalArgumentException e1) {
					e1.printStackTrace();
				} catch (IllegalAccessException e1) {
					e1.printStackTrace();
				}
				
				for (E e2 : list) {
					for (Field field2 : fields) {
						field2.setAccessible(true);
						boolean hasSonAnnot = field2.isAnnotationPresent(son.class);
						if (!hasSonAnnot) {
							continue;
						}
						Object sonValue = null;
						try {
							sonValue = field2.get(e2);
						} catch (IllegalArgumentException e1) {
							e1.printStackTrace();
						} catch (IllegalAccessException e1) {
							e1.printStackTrace();
						}
						

						if (fatherValue == sonValue) {
							isRoot = false;
							break;
						}
						
						
					}
				}
				if (isRoot == true) {
					roots.add(e);
				}
			}
		}
		list.removeAll(roots);
		return roots;
	}

}
